import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vischat/core/controller/auth_service.dart';
import 'package:vischat/core/controller/global_service.dart';
import 'package:vischat/core/utils/app_toast.dart';
import 'package:vischat/core/utils/tencent/tencent_init.dart';
import 'package:vischat/generated/icons/app_icons.dart';
import 'package:vischat/generated/route_table.dart';

class HomeController extends GetxController {
  final AuthService _auth;
  HomeController(this._auth);

  DateTime? _lastBackPressedTime;

  final _activeIndex = 1.obs; // 底部导航栏页面下标
  final List<IconData> _bottomNavigationMenus = [
    AppIcons.message,
    AppIcons.arrow_right_fat,
    AppIcons.personal,
  ];

  int get unread => _auth.unread.value;
  int get activeIndex => _activeIndex.value;
  List<IconData> get bottomNavigationMenus => _bottomNavigationMenus;
  GlobalService get global => Get.find();

  @override
  void onInit() {
    TencentInit.initSDK();
    super.onInit();
  }

  void onItemSelected(int index) {
    if (_auth.loginState == LoginState.loggedIn) {
      _activeIndex.value = index;
    } else {
      Get.toNamed(RouteTable.LOGIN);
    }
  }

  /// 点击两次返回键退出app
  Future<bool> handleWillPop(BuildContext context) async {
    final now = DateTime.now();
    final bool mustWait =
        _lastBackPressedTime == null ||
        now.difference(_lastBackPressedTime!) > const Duration(seconds: 2);

    if (mustWait) {
      _lastBackPressedTime = now;
      AppToast.showToast('toast.exitApp'.tr);
      return false;
    }
    Get.reset();
    return true;
  }
}
